package Comp;

/**
 * The Comp Tokenize operations break a COMP string up into tokens that we can 
 * process easier than just a big long string.<br>
 * <u>Internal Variables Used:</u><p>
 * terminals: string of math characters which are not labels or numbers<br>
 * tokenized_string: string array of usable output for the evaluator and prefixer<br>
 * array_index: index of tokenized string that we are writing to<br>
 * pos: iterator of position of character to compare<br>
 * <p><b>Original Author:</b>  Peter
 */
public class Tokenize {

    /**
    * Tokenizes COMP expressions by breaking the comp expression into a tokenized version that is broken at terminal 
    * character, where the terminal characters are defined as {'(',')','*','-','+','/','='}
    * For example, input of AB=(A-B/C+E) would return AB,=,(,A,-,B,/,C,+,E,)
    * <p>
    * <b>Change Log:</b><br>
    * 05/03/08 - Initial Code - Peter Dietz<br>
    * 05/10/08 - Fixed case for a=b - Peter Dietz<br>
    * <p>
    * <b>Error Conditions Tested:</b><br>
    * none yet <br>
    * <p>
    * <b>Date of module being installed:</b> 05/03/08
    * <p><b>Original Author:</b>  Peter Dietz
    * @param comp_expression The exact parameter or operand of a COMP instruction
    * @return String array that has a single element at each index
    */
    public String[] tokenizeComp(String comp_expression){
        String terminals = "()+-/*=";

        String[] tokenized_string = new String[comp_expression.length()];
        for(int index=0; index<tokenized_string.length; index++){
            tokenized_string[index]="";
        }
        int array_index=0;
        int pos=0;

        while(comp_expression.length() > 0 && (comp_expression.contains("(") || comp_expression.contains(")") ||comp_expression.contains("+") ||comp_expression.contains("-") ||comp_expression.contains("/") ||comp_expression.contains("*") ||comp_expression.contains("=") )){
            if(terminals.contains(String.valueOf(comp_expression.charAt(pos)))){
                if(pos==0){
                    tokenized_string[array_index]=String.valueOf(comp_expression.charAt(pos));
                    array_index++;
                    comp_expression=comp_expression.substring(1);
                } else {
                    tokenized_string[array_index]=comp_expression.substring(0,pos);
                    array_index++;
                    tokenized_string[array_index]=String.valueOf(comp_expression.charAt(pos));
                    array_index++;
                    comp_expression=comp_expression.substring(pos+1);
                }
                pos=0;
            } else {
                pos++;
            }
        }
 
        if (comp_expression.length()>0){
            tokenized_string[array_index] = comp_expression;
        }
        return tokenized_string;
    }   

}
